import React, {Component} from 'react';
import {reqMessages, reqDeleteMessage} from "../../../api";
import {formatDate} from "../../../util";
import {
    Button, Card, message, Tag,
    Popconfirm, Space, Table, Typography
} from "antd";
import {DeleteOutlined} from '@ant-design/icons';

const {Link} = Typography;

class Message extends Component {

    state = {
        dataSource: [],
        current: 1,
        total: 0,
    }

    componentDidMount() {
        this.initDataSource();
    }

    initDataSource = async () => {
        let {current} = this.state;
        let {data} = await reqMessages(current);
        let {total, list} = data;
        this.setState({total, dataSource: list});
    }

    deleteMessage = async (data) => {
        let {status, msg} = await reqDeleteMessage(data.id);
        if (status === 0) {
            message.success(msg);
            this.initDataSource();
            return;
        }
        message.error(msg);
    }

    changePage = (pageInfo) => {
        let {current} = pageInfo;
        this.setState({current}, () => {
            this.initDataSource();
        });
    }

    columns = [
        {
            title: '昵称',
            dataIndex: 'nickName',
            render: (data) => {
                return (<Tag color="volcano">{data}</Tag>)
            }
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            render: (data) => {
                return ( <Tag color="cyan">{data}</Tag>)
            }
        },
        {
            title: '内容',
            dataIndex: 'content',
            render: (data) => {
                return (<Link>{data}</Link>)
            }
        },
        {
            title: '留言时间',
            dataIndex: 'createTime',
            render: (data) => {
                return formatDate("YYYY-MM-dd HH:mm:ss", data);
            }
        },
        {
            title: '操作',
            render: (data) => {
                return (
                    <Space size="small">
                        <Popconfirm
                            title="确定删除吗？"
                            onConfirm={() => this.deleteMessage(data)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button size="small" danger icon={<DeleteOutlined/>}/>
                        </Popconfirm>
                    </Space>
                )
            }
        },
    ];

    render() {
        let {dataSource, total} = this.state;
        return (
            <Card>
                <Table
                    rowKey="id"
                    size="small"
                    onChange={this.changePage}
                    pagination={{total, showTotal: (total) => `共 ${total} 条`}}
                    dataSource={dataSource}
                    columns={this.columns}/>
            </Card>
        );
    }
}

export default Message;
